require 'open-uri'
require 'rexml/document'
require 'erb'

class FlickrImage < Artifact

  include ERB::Util
  
  def self.search(user,context_elements)
    tags = []
    context_elements.each do |e| 
      tags << e.artifact.title unless e.artifact.title.match('$http://')
    end  
    tags = tags.join('&tag=') # html_escape not really doing what I want ...
    tags.gsub!(' ','%20')
    flickr_images = grab_photo_uris('d4aa294487e70a1211474cfb9c961e84',tags)
    flickr_images.each do |f|
      flickr_image = Artifact.find_by_title(f[:uri])
      if flickr_image.nil?
        flickr_image = new
        flickr_image.title = f[:uri]
        flickr_image.content = f[:title].to_s
        flickr_image.save!
      end
      Relation.add_relation_to_context(flickr_image,user, context_elements)
    end
  end
  
  def self.small_photo_uri(photo)
    server = photo.attribute('server')
    id = photo.attribute('id')
    secret = photo.attribute('secret')
    return "http://static.flickr.com/#{server}/#{id}_#{secret}_m.jpg"
  end
  
  def self.grab_photo_uris(api_key, tag)
    uri= "http://www.flickr.com/services/rest?method=flickr.photos.search"+
       "&api_key=#{api_key}&tags=#{tag}&per_page=5&content_type=2"
    logger.info(uri)
    response = open(uri).read
    
    doc = REXML::Document.new(response)
    photos = []
    REXML::XPath.each(doc,'//photo') do |photo|
      photos << {:uri=>small_photo_uri(photo),:title=>photo.attribute('title')} if photo
    end
    return photos
  end
end
